home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / ftplib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  28KB  |  1,012 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """An FTP client class and some helper functions.
  5.  
  6. Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds
  7.  
  8. Example:
  9.  
  10. >>> from ftplib import FTP
  11. >>> ftp = FTP('ftp.python.org') # connect to host, default port
  12. >>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
  13. '230 Guest login ok, access restrictions apply.'
  14. >>> ftp.retrlines('LIST') # list directory contents
  15. total 9
  16. drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
  17. drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
  18. drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
  19. drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
  20. d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
  21. drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
  22. drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
  23. drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
  24. -rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg
  25. '226 Transfer complete.'
  26. >>> ftp.quit()
  27. '221 Goodbye.'
  28. >>>
  29.  
  30. A nice test that reveals some of the network dialogue would be:
  31. python ftplib.py -d localhost -l -p -l
  32. """
  33. import os
  34. import sys
  35.  
  36. try:
  37.     import SOCKS
  38.     socket = SOCKS
  39.     del SOCKS
  40.     from socket import getfqdn
  41.     socket.getfqdn = getfqdn
  42.     del getfqdn
  43. except ImportError:
  44.     import socket
  45.  
  46. from socket import _GLOBAL_DEFAULT_TIMEOUT
  47. __all__ = [
  48.     'FTP',
  49.     'Netrc']
  50. MSG_OOB = 1
  51. FTP_PORT = 21
  52.  
  53. class Error(Exception):
  54.     pass
  55.  
  56.  
  57. class error_reply(Error):
  58.     pass
  59.  
  60.  
  61. class error_temp(Error):
  62.     pass
  63.  
  64.  
  65. class error_perm(Error):
  66.     pass
  67.  
  68.  
  69. class error_proto(Error):
  70.     pass
  71.  
  72. all_errors = (Error, IOError, EOFError)
  73. CRLF = '\r\n'
  74.  
  75. class FTP:
  76.     """An FTP client class.
  77.  
  78.     To create a connection, call the class using these arguments:
  79.             host, user, passwd, acct, timeout
  80.  
  81.     The first four arguments are all strings, and have default value ''.
  82.     timeout must be numeric and defaults to None if not passed,
  83.     meaning that no timeout will be set on any ftp socket(s)
  84.     If a timeout is passed, then this is now the default timeout for all ftp
  85.     socket operations for this instance.
  86.  
  87.     Then use self.connect() with optional host and port argument.
  88.  
  89.     To download a file, use ftp.retrlines('RETR ' + filename),
  90.     or ftp.retrbinary() with slightly different arguments.
  91.     To upload a file, use ftp.storlines() or ftp.storbinary(),
  92.     which have an open file as argument (see their definitions
  93.     below for details).
  94.     The download/upload functions first issue appropriate TYPE
  95.     and PORT or PASV commands.
  96. """
  97.     debugging = 0
  98.     host = ''
  99.     port = FTP_PORT
  100.     sock = None
  101.     file = None
  102.     welcome = None
  103.     passiveserver = 1
  104.     
  105.     def __init__(self, host = '', user = '', passwd = '', acct = '', timeout = _GLOBAL_DEFAULT_TIMEOUT):
  106.         self.timeout = timeout
  107.         if host:
  108.             self.connect(host)
  109.             if user:
  110.                 self.login(user, passwd, acct)
  111.             
  112.         
  113.  
  114.     
  115.     def connect(self, host = '', port = 0, timeout = -999):
  116.         '''Connect to host.  Arguments are:
  117.          - host: hostname to connect to (string, default previous host)
  118.          - port: port to connect to (integer, default previous port)
  119.         '''
  120.         if host != '':
  121.             self.host = host
  122.         
  123.         if port > 0:
  124.             self.port = port
  125.         
  126.         if timeout != -999:
  127.             self.timeout = timeout
  128.         
  129.         self.sock = socket.create_connection((self.host, self.port), self.timeout)
  130.         self.af = self.sock.family
  131.         self.file = self.sock.makefile('rb')
  132.         self.welcome = self.getresp()
  133.         return self.welcome
  134.  
  135.     
  136.     def getwelcome(self):
  137.         '''Get the welcome message from the server.
  138.         (this is read and squirreled away by connect())'''
  139.         if self.debugging:
  140.             print '*welcome*', self.sanitize(self.welcome)
  141.         
  142.         return self.welcome
  143.  
  144.     
  145.     def set_debuglevel(self, level):
  146.         '''Set the debugging level.
  147.         The required argument level means:
  148.         0: no debugging output (default)
  149.         1: print commands and responses but not body text etc.
  150.         2: also print raw lines read and sent before stripping CR/LF'''
  151.         self.debugging = level
  152.  
  153.     debug = set_debuglevel
  154.     
  155.     def set_pasv(self, val):
  156.         '''Use passive or active mode for data transfers.
  157.         With a false argument, use the normal PORT mode,
  158.         With a true argument, use the PASV command.'''
  159.         self.passiveserver = val
  160.  
  161.     
  162.     def sanitize(self, s):
  163.         if s[:5] == 'pass ' or s[:5] == 'PASS ':
  164.             i = len(s)
  165.             while i > 5 and s[i - 1] in '\r\n':
  166.                 i = i - 1
  167.             s = s[:5] + '*' * (i - 5) + s[i:]
  168.         
  169.         return repr(s)
  170.  
  171.     
  172.     def putline(self, line):
  173.         line = line + CRLF
  174.         if self.debugging > 1:
  175.             print '*put*', self.sanitize(line)
  176.         
  177.         self.sock.sendall(line)
  178.  
  179.     
  180.     def putcmd(self, line):
  181.         if self.debugging:
  182.             print '*cmd*', self.sanitize(line)
  183.         
  184.         self.putline(line)
  185.  
  186.     
  187.     def getline(self):
  188.         line = self.file.readline()
  189.         if self.debugging > 1:
  190.             print '*get*', self.sanitize(line)
  191.         
  192.         if not line:
  193.             raise EOFError
  194.         line
  195.         if line[-2:] == CRLF:
  196.             line = line[:-2]
  197.         elif line[-1:] in CRLF:
  198.             line = line[:-1]
  199.         
  200.         return line
  201.  
  202.     
  203.     def getmultiline(self):
  204.         line = self.getline()
  205.         if line[3:4] == '-':
  206.             code = line[:3]
  207.             while None:
  208.                 nextline = self.getline()
  209.                 line = line + '\n' + nextline
  210.                 if nextline[:3] == code and nextline[3:4] != '-':
  211.                     break
  212.                     continue
  213.                 continue
  214.         line[3:4] == '-'
  215.         return line
  216.  
  217.     
  218.     def getresp(self):
  219.         resp = self.getmultiline()
  220.         if self.debugging:
  221.             print '*resp*', self.sanitize(resp)
  222.         
  223.         self.lastresp = resp[:3]
  224.         c = resp[:1]
  225.         if c in ('1', '2', '3'):
  226.             return resp
  227.         if c == '4':
  228.             raise error_temp, resp
  229.         c == '4'
  230.         if c == '5':
  231.             raise error_perm, resp
  232.         c == '5'
  233.         raise error_proto, resp
  234.  
  235.     
  236.     def voidresp(self):
  237.         """Expect a response beginning with '2'."""
  238.         resp = self.getresp()
  239.         if resp[:1] != '2':
  240.             raise error_reply, resp
  241.         resp[:1] != '2'
  242.         return resp
  243.  
  244.     
  245.     def abort(self):
  246.         """Abort a file transfer.  Uses out-of-band data.
  247.         This does not follow the procedure from the RFC to send Telnet
  248.         IP and Synch; that doesn't seem to work with the servers I've
  249.         tried.  Instead, just send the ABOR command as OOB data."""
  250.         line = 'ABOR' + CRLF
  251.         if self.debugging > 1:
  252.             print '*put urgent*', self.sanitize(line)
  253.         
  254.         self.sock.sendall(line, MSG_OOB)
  255.         resp = self.getmultiline()
  256.         if resp[:3] not in ('426', '226'):
  257.             raise error_proto, resp
  258.         resp[:3] not in ('426', '226')
  259.  
  260.     
  261.     def sendcmd(self, cmd):
  262.         '''Send a command and return the response.'''
  263.         self.putcmd(cmd)
  264.         return self.getresp()
  265.  
  266.     
  267.     def voidcmd(self, cmd):
  268.         """Send a command and expect a response beginning with '2'."""
  269.         self.putcmd(cmd)
  270.         return self.voidresp()
  271.  
  272.     
  273.     def sendport(self, host, port):
  274.         '''Send a PORT command with the current host and the given
  275.         port number.
  276.         '''
  277.         hbytes = host.split('.')
  278.         pbytes = [
  279.             repr(port // 256),
  280.             repr(port % 256)]
  281.         bytes = hbytes + pbytes
  282.         cmd = 'PORT ' + ','.join(bytes)
  283.         return self.voidcmd(cmd)
  284.  
  285.     
  286.     def sendeprt(self, host, port):
  287.         '''Send a EPRT command with the current host and the given port number.'''
  288.         af = 0
  289.         if self.af == socket.AF_INET:
  290.             af = 1
  291.         
  292.         if self.af == socket.AF_INET6:
  293.             af = 2
  294.         
  295.         if af == 0:
  296.             raise error_proto, 'unsupported address family'
  297.         af == 0
  298.         fields = [
  299.             '',
  300.             repr(af),
  301.             host,
  302.             repr(port),
  303.             '']
  304.         cmd = 'EPRT ' + '|'.join(fields)
  305.         return self.voidcmd(cmd)
  306.  
  307.     
  308.     def makeport(self):
  309.         '''Create a new socket and send a PORT command for it.'''
  310.         msg = 'getaddrinfo returns an empty list'
  311.         sock = None
  312.         for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
  313.             (af, socktype, proto, canonname, sa) = res
  314.             
  315.             try:
  316.                 sock = socket.socket(af, socktype, proto)
  317.                 sock.bind(sa)
  318.             except socket.error:
  319.                 msg = None
  320.                 if sock:
  321.                     sock.close()
  322.                 
  323.                 sock = None
  324.                 continue
  325.  
  326.             break
  327.         
  328.         if not sock:
  329.             raise socket.error, msg
  330.         sock
  331.         sock.listen(1)
  332.         port = sock.getsockname()[1]
  333.         host = self.sock.getsockname()[0]
  334.         if self.af == socket.AF_INET:
  335.             resp = self.sendport(host, port)
  336.         else:
  337.             resp = self.sendeprt(host, port)
  338.         return sock
  339.  
  340.     
  341.     def makepasv(self):
  342.         if self.af == socket.AF_INET:
  343.             (host, port) = parse227(self.sendcmd('PASV'))
  344.         else:
  345.             (host, port) = parse229(self.sendcmd('EPSV'), self.sock.getpeername())
  346.         return (host, port)
  347.  
  348.     
  349.     def ntransfercmd(self, cmd, rest = None):
  350.         """Initiate a transfer over the data connection.
  351.  
  352.         If the transfer is active, send a port command and the
  353.         transfer command, and accept the connection.  If the server is
  354.         passive, send a pasv command, connect to it, and start the
  355.         transfer command.  Either way, return the socket for the
  356.         connection and the expected size of the transfer.  The
  357.         expected size may be None if it could not be determined.
  358.  
  359.         Optional `rest' argument can be a string that is sent as the
  360.         argument to a REST command.  This is essentially a server
  361.         marker used to tell the server to skip over any data up to the
  362.         given marker.
  363.         """
  364.         size = None
  365.         if self.passiveserver:
  366.             (host, port) = self.makepasv()
  367.             conn = socket.create_connection((host, port), self.timeout)
  368.             if rest is not None:
  369.                 self.sendcmd('REST %s' % rest)
  370.             
  371.             resp = self.sendcmd(cmd)
  372.             if resp[0] == '2':
  373.                 resp = self.getresp()
  374.             
  375.             if resp[0] != '1':
  376.                 raise error_reply, resp
  377.             resp[0] != '1'
  378.         else:
  379.             sock = self.makeport()
  380.             if rest is not None:
  381.                 self.sendcmd('REST %s' % rest)
  382.             
  383.             resp = self.sendcmd(cmd)
  384.             if resp[0] == '2':
  385.                 resp = self.getresp()
  386.             
  387.             if resp[0] != '1':
  388.                 raise error_reply, resp
  389.             resp[0] != '1'
  390.             (conn, sockaddr) = sock.accept()
  391.         if resp[:3] == '150':
  392.             size = parse150(resp)
  393.         
  394.         return (conn, size)
  395.  
  396.     
  397.     def transfercmd(self, cmd, rest = None):
  398.         '''Like ntransfercmd() but returns only the socket.'''
  399.         return self.ntransfercmd(cmd, rest)[0]
  400.  
  401.     
  402.     def login(self, user = '', passwd = '', acct = ''):
  403.         '''Login, default anonymous.'''
  404.         if not user:
  405.             user = 'anonymous'
  406.         
  407.         if not passwd:
  408.             passwd = ''
  409.         
  410.         if not acct:
  411.             acct = ''
  412.         
  413.         if user == 'anonymous' and passwd in ('', '-'):
  414.             passwd = passwd + 'anonymous@'
  415.         
  416.         resp = self.sendcmd('USER ' + user)
  417.         if resp[0] == '3':
  418.             resp = self.sendcmd('PASS ' + passwd)
  419.         
  420.         if resp[0] == '3':
  421.             resp = self.sendcmd('ACCT ' + acct)
  422.         
  423.         if resp[0] != '2':
  424.             raise error_reply, resp
  425.         resp[0] != '2'
  426.         return resp
  427.  
  428.     
  429.     def retrbinary(self, cmd, callback, blocksize = 8192, rest = None):
  430.         '''Retrieve data in binary mode.  A new port is created for you.
  431.  
  432.         Args:
  433.           cmd: A RETR command.
  434.           callback: A single parameter callable to be called on each
  435.                     block of data read.
  436.           blocksize: The maximum number of bytes to read from the
  437.                      socket at one time.  [default: 8192]
  438.           rest: Passed to transfercmd().  [default: None]
  439.  
  440.         Returns:
  441.           The response code.
  442.         '''
  443.         self.voidcmd('TYPE I')
  444.         conn = self.transfercmd(cmd, rest)
  445.         while None:
  446.             data = conn.recv(blocksize)
  447.             if not data:
  448.                 break
  449.             
  450.             continue
  451.             conn.close()
  452.             return self.voidresp()
  453.  
  454.     
  455.     def retrlines(self, cmd, callback = None):
  456.         '''Retrieve data in line mode.  A new port is created for you.
  457.  
  458.         Args:
  459.           cmd: A RETR, LIST, NLST, or MLSD command.
  460.           callback: An optional single parameter callable that is called
  461.                     for each line with the trailing CRLF stripped.
  462.                     [default: print_line()]
  463.  
  464.         Returns:
  465.           The response code.
  466.         '''
  467.         if callback is None:
  468.             callback = print_line
  469.         
  470.         resp = self.sendcmd('TYPE A')
  471.         conn = self.transfercmd(cmd)
  472.         fp = conn.makefile('rb')
  473.         while None:
  474.             line = fp.readline()
  475.             if self.debugging > 2:
  476.                 print '*retr*', repr(line)
  477.             
  478.             if not line:
  479.                 break
  480.             
  481.             if line[-2:] == CRLF:
  482.                 line = line[:-2]
  483.             elif line[-1:] == '\n':
  484.                 line = line[:-1]
  485.             
  486.             continue
  487.             fp.close()
  488.             conn.close()
  489.             return self.voidresp()
  490.  
  491.     
  492.     def storbinary(self, cmd, fp, blocksize = 8192, callback = None):
  493.         '''Store a file in binary mode.  A new port is created for you.
  494.  
  495.         Args:
  496.           cmd: A STOR command.
  497.           fp: A file-like object with a read(num_bytes) method.
  498.           blocksize: The maximum data size to read from fp and send over
  499.                      the connection at once.  [default: 8192]
  500.           callback: An optional single parameter callable that is called on
  501.                     on each block of data after it is sent.  [default: None]
  502.  
  503.         Returns:
  504.           The response code.
  505.         '''
  506.         self.voidcmd('TYPE I')
  507.         conn = self.transfercmd(cmd)
  508.         while None:
  509.             buf = fp.read(blocksize)
  510.             if not buf:
  511.                 break
  512.             
  513.             if callback:
  514.                 callback(buf)
  515.                 continue
  516.             continue
  517.             conn.close()
  518.             return self.voidresp()
  519.  
  520.     
  521.     def storlines(self, cmd, fp, callback = None):
  522.         '''Store a file in line mode.  A new port is created for you.
  523.  
  524.         Args:
  525.           cmd: A STOR command.
  526.           fp: A file-like object with a readline() method.
  527.           callback: An optional single parameter callable that is called on
  528.                     on each line after it is sent.  [default: None]
  529.  
  530.         Returns:
  531.           The response code.
  532.         '''
  533.         self.voidcmd('TYPE A')
  534.         conn = self.transfercmd(cmd)
  535.         while None:
  536.             buf = fp.readline()
  537.             if not buf:
  538.                 break
  539.             
  540.             if buf[-2:] != CRLF:
  541.                 if buf[-1] in CRLF:
  542.                     buf = buf[:-1]
  543.                 
  544.                 buf = buf + CRLF
  545.             
  546.             if callback:
  547.                 callback(buf)
  548.                 continue
  549.             continue
  550.             conn.close()
  551.             return self.voidresp()
  552.  
  553.     
  554.     def acct(self, password):
  555.         '''Send new account name.'''
  556.         cmd = 'ACCT ' + password
  557.         return self.voidcmd(cmd)
  558.  
  559.     
  560.     def nlst(self, *args):
  561.         '''Return a list of files in a given directory (default the current).'''
  562.         cmd = 'NLST'
  563.         for arg in args:
  564.             cmd = cmd + ' ' + arg
  565.         
  566.         files = []
  567.         self.retrlines(cmd, files.append)
  568.         return files
  569.  
  570.     
  571.     def dir(self, *args):
  572.         '''List a directory in long form.
  573.         By default list current directory to stdout.
  574.         Optional last argument is callback function; all
  575.         non-empty arguments before it are concatenated to the
  576.         LIST command.  (This *should* only be used for a pathname.)'''
  577.         cmd = 'LIST'
  578.         func = None
  579.         if args[-1:] and type(args[-1]) != type(''):
  580.             args = args[:-1]
  581.             func = args[-1]
  582.         
  583.         for arg in args:
  584.             if arg:
  585.                 cmd = cmd + ' ' + arg
  586.                 continue
  587.         
  588.         self.retrlines(cmd, func)
  589.  
  590.     
  591.     def rename(self, fromname, toname):
  592.         '''Rename a file.'''
  593.         resp = self.sendcmd('RNFR ' + fromname)
  594.         if resp[0] != '3':
  595.             raise error_reply, resp
  596.         resp[0] != '3'
  597.         return self.voidcmd('RNTO ' + toname)
  598.  
  599.     
  600.     def delete(self, filename):
  601.         '''Delete a file.'''
  602.         resp = self.sendcmd('DELE ' + filename)
  603.         if resp[:3] in ('250', '200'):
  604.             return resp
  605.         raise error_reply, resp
  606.  
  607.     
  608.     def cwd(self, dirname):
  609.         '''Change to a directory.'''
  610.         if dirname == '..':
  611.             
  612.             try:
  613.                 return self.voidcmd('CDUP')
  614.             except error_perm:
  615.                 msg = None
  616.                 if msg.args[0][:3] != '500':
  617.                     raise 
  618.                 msg.args[0][:3] != '500'
  619.             except:
  620.                 None<EXCEPTION MATCH>error_perm
  621.             
  622.  
  623.         None<EXCEPTION MATCH>error_perm
  624.         if dirname == '':
  625.             dirname = '.'
  626.         
  627.         cmd = 'CWD ' + dirname
  628.         return self.voidcmd(cmd)
  629.  
  630.     
  631.     def size(self, filename):
  632.         '''Retrieve the size of a file.'''
  633.         resp = self.sendcmd('SIZE ' + filename)
  634.         if resp[:3] == '213':
  635.             s = resp[3:].strip()
  636.             
  637.             try:
  638.                 return int(s)
  639.             except (OverflowError, ValueError):
  640.                 return long(s)
  641.             
  642.  
  643.         None<EXCEPTION MATCH>(OverflowError, ValueError)
  644.  
  645.     
  646.     def mkd(self, dirname):
  647.         '''Make a directory, return its full pathname.'''
  648.         resp = self.sendcmd('MKD ' + dirname)
  649.         return parse257(resp)
  650.  
  651.     
  652.     def rmd(self, dirname):
  653.         '''Remove a directory.'''
  654.         return self.voidcmd('RMD ' + dirname)
  655.  
  656.     
  657.     def pwd(self):
  658.         '''Return current working directory.'''
  659.         resp = self.sendcmd('PWD')
  660.         return parse257(resp)
  661.  
  662.     
  663.     def quit(self):
  664.         '''Quit, and close the connection.'''
  665.         resp = self.voidcmd('QUIT')
  666.         self.close()
  667.         return resp
  668.  
  669.     
  670.     def close(self):
  671.         '''Close the connection without assuming anything about it.'''
  672.         if self.file:
  673.             self.file.close()
  674.             self.sock.close()
  675.             self.file = None
  676.             self.sock = None
  677.         
  678.  
  679.  
  680. _150_re = None
  681.  
  682. def parse150(resp):
  683.     """Parse the '150' response for a RETR request.
  684.     Returns the expected transfer size or None; size is not guaranteed to
  685.     be present in the 150 message.
  686.     """
  687.     global _150_re
  688.     if resp[:3] != '150':
  689.         raise error_reply, resp
  690.     resp[:3] != '150'
  691.     if _150_re is None:
  692.         import re as re
  693.         _150_re = re.compile('150 .* \\((\\d+) bytes\\)', re.IGNORECASE)
  694.     
  695.     m = _150_re.match(resp)
  696.     if not m:
  697.         return None
  698.     s = m.group(1)
  699.     
  700.     try:
  701.         return int(s)
  702.     except (OverflowError, ValueError):
  703.         m
  704.         m
  705.         return long(s)
  706.  
  707.  
  708. _227_re = None
  709.  
  710. def parse227(resp):
  711.     """Parse the '227' response for a PASV request.
  712.     Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
  713.     Return ('host.addr.as.numbers', port#) tuple."""
  714.     global _227_re
  715.     if resp[:3] != '227':
  716.         raise error_reply, resp
  717.     resp[:3] != '227'
  718.     if _227_re is None:
  719.         import re
  720.         _227_re = re.compile('(\\d+),(\\d+),(\\d+),(\\d+),(\\d+),(\\d+)')
  721.     
  722.     m = _227_re.search(resp)
  723.     if not m:
  724.         raise error_proto, resp
  725.     m
  726.     numbers = m.groups()
  727.     host = '.'.join(numbers[:4])
  728.     port = (int(numbers[4]) << 8) + int(numbers[5])
  729.     return (host, port)
  730.  
  731.  
  732. def parse229(resp, peer):
  733.     """Parse the '229' response for a EPSV request.
  734.     Raises error_proto if it does not contain '(|||port|)'
  735.     Return ('host.addr.as.numbers', port#) tuple."""
  736.     if resp[:3] != '229':
  737.         raise error_reply, resp
  738.     resp[:3] != '229'
  739.     left = resp.find('(')
  740.     if left < 0:
  741.         raise error_proto, resp
  742.     left < 0
  743.     right = resp.find(')', left + 1)
  744.     if right < 0:
  745.         raise error_proto, resp
  746.     right < 0
  747.     if resp[left + 1] != resp[right - 1]:
  748.         raise error_proto, resp
  749.     resp[left + 1] != resp[right - 1]
  750.     parts = resp[left + 1:right].split(resp[left + 1])
  751.     if len(parts) != 5:
  752.         raise error_proto, resp
  753.     len(parts) != 5
  754.     host = peer[0]
  755.     port = int(parts[3])
  756.     return (host, port)
  757.  
  758.  
  759. def parse257(resp):
  760.     """Parse the '257' response for a MKD or PWD request.
  761.     This is a response to a MKD or PWD request: a directory name.
  762.     Returns the directoryname in the 257 reply."""
  763.     if resp[:3] != '257':
  764.         raise error_reply, resp
  765.     resp[:3] != '257'
  766.     if resp[3:5] != ' "':
  767.         return ''
  768.     dirname = ''
  769.     i = 5
  770.     n = len(resp)
  771.     while i < n:
  772.         c = resp[i]
  773.         i = i + 1
  774.         dirname = dirname + c
  775.         continue
  776.         None if c == '"' else resp[3:5] != ' "'
  777.     return dirname
  778.  
  779.  
  780. def print_line(line):
  781.     '''Default retrlines callback to print a line.'''
  782.     print line
  783.  
  784.  
  785. def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
  786.     '''Copy file from one FTP-instance to another.'''
  787.     if not targetname:
  788.         targetname = sourcename
  789.     
  790.     type = 'TYPE ' + type
  791.     source.voidcmd(type)
  792.     target.voidcmd(type)
  793.     (sourcehost, sourceport) = parse227(source.sendcmd('PASV'))
  794.     target.sendport(sourcehost, sourceport)
  795.     treply = target.sendcmd('STOR ' + targetname)
  796.     if treply[:3] not in ('125', '150'):
  797.         raise error_proto
  798.     treply[:3] not in ('125', '150')
  799.     sreply = source.sendcmd('RETR ' + sourcename)
  800.     if sreply[:3] not in ('125', '150'):
  801.         raise error_proto
  802.     sreply[:3] not in ('125', '150')
  803.     source.voidresp()
  804.     target.voidresp()
  805.  
  806.  
  807. class Netrc:
  808.     """Class to parse & provide access to 'netrc' format files.
  809.  
  810.     See the netrc(4) man page for information on the file format.
  811.  
  812.     WARNING: This class is obsolete -- use module netrc instead.
  813.  
  814.     """
  815.     __defuser = None
  816.     __defpasswd = None
  817.     __defacct = None
  818.     
  819.     def __init__(self, filename = None):
  820.         if filename is None:
  821.             if 'HOME' in os.environ:
  822.                 filename = os.path.join(os.environ['HOME'], '.netrc')
  823.             else:
  824.                 raise IOError, 'specify file to load or set $HOME'
  825.         'HOME' in os.environ
  826.         self._Netrc__hosts = { }
  827.         self._Netrc__macros = { }
  828.         fp = open(filename, 'r')
  829.         in_macro = 0
  830.         while None:
  831.             line = fp.readline()
  832.             if not line:
  833.                 break
  834.             
  835.             if in_macro and line.strip():
  836.                 macro_lines.append(line)
  837.                 continue
  838.             elif in_macro:
  839.                 self._Netrc__macros[macro_name] = tuple(macro_lines)
  840.                 in_macro = 0
  841.             
  842.             words = line.split()
  843.             host = None
  844.             user = None
  845.             passwd = None
  846.             acct = None
  847.             default = 0
  848.             i = 0
  849.             while i < len(words):
  850.                 w1 = words[i]
  851.                 if i + 1 < len(words):
  852.                     w2 = words[i + 1]
  853.                 else:
  854.                     w2 = None
  855.                 if w1 == 'default':
  856.                     default = 1
  857.                 elif w1 == 'machine' and w2:
  858.                     host = w2.lower()
  859.                     i = i + 1
  860.                 elif w1 == 'login' and w2:
  861.                     user = w2
  862.                     i = i + 1
  863.                 elif w1 == 'password' and w2:
  864.                     passwd = w2
  865.                     i = i + 1
  866.                 elif w1 == 'account' and w2:
  867.                     acct = w2
  868.                     i = i + 1
  869.                 elif w1 == 'macdef' and w2:
  870.                     macro_name = w2
  871.                     macro_lines = []
  872.                     in_macro = 1
  873.                     break
  874.                 
  875.                 i = i + 1
  876.             if default:
  877.                 if not user:
  878.                     pass
  879.                 self._Netrc__defuser = self._Netrc__defuser
  880.                 if not passwd:
  881.                     pass
  882.                 self._Netrc__defpasswd = self._Netrc__defpasswd
  883.                 if not acct:
  884.                     pass
  885.                 self._Netrc__defacct = self._Netrc__defacct
  886.             
  887.             if host:
  888.                 if host in self._Netrc__hosts:
  889.                     (ouser, opasswd, oacct) = self._Netrc__hosts[host]
  890.                     if not user:
  891.                         pass
  892.                     user = ouser
  893.                     if not passwd:
  894.                         pass
  895.                     passwd = opasswd
  896.                     if not acct:
  897.                         pass
  898.                     acct = oacct
  899.                 
  900.                 self._Netrc__hosts[host] = (user, passwd, acct)
  901.                 continue
  902.             continue
  903.             fp.close()
  904.             return None
  905.  
  906.     
  907.     def get_hosts(self):
  908.         '''Return a list of hosts mentioned in the .netrc file.'''
  909.         return self._Netrc__hosts.keys()
  910.  
  911.     
  912.     def get_account(self, host):
  913.         '''Returns login information for the named host.
  914.  
  915.         The return value is a triple containing userid,
  916.         password, and the accounting field.
  917.  
  918.         '''
  919.         host = host.lower()
  920.         user = None
  921.         passwd = None
  922.         acct = None
  923.         if host in self._Netrc__hosts:
  924.             (user, passwd, acct) = self._Netrc__hosts[host]
  925.         
  926.         if not user:
  927.             pass
  928.         user = self._Netrc__defuser
  929.         if not passwd:
  930.             pass
  931.         passwd = self._Netrc__defpasswd
  932.         if not acct:
  933.             pass
  934.         acct = self._Netrc__defacct
  935.         return (user, passwd, acct)
  936.  
  937.     
  938.     def get_macros(self):
  939.         '''Return a list of all defined macro names.'''
  940.         return self._Netrc__macros.keys()
  941.  
  942.     
  943.     def get_macro(self, macro):
  944.         '''Return a sequence of lines which define a named macro.'''
  945.         return self._Netrc__macros[macro]
  946.  
  947.  
  948.  
  949. def test():
  950.     '''Test program.
  951.     Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...
  952.  
  953.     -d dir
  954.     -l list
  955.     -p password
  956.     '''
  957.     if len(sys.argv) < 2:
  958.         print test.__doc__
  959.         sys.exit(0)
  960.     
  961.     debugging = 0
  962.     rcfile = None
  963.     while sys.argv[1] == '-d':
  964.         debugging = debugging + 1
  965.         del sys.argv[1]
  966.     if sys.argv[1][:2] == '-r':
  967.         rcfile = sys.argv[1][2:]
  968.         del sys.argv[1]
  969.     
  970.     host = sys.argv[1]
  971.     ftp = FTP(host)
  972.     ftp.set_debuglevel(debugging)
  973.     userid = passwd = acct = ''
  974.     
  975.     try:
  976.         netrc = Netrc(rcfile)
  977.     except IOError:
  978.         if rcfile is not None:
  979.             sys.stderr.write('Could not open account file -- using anonymous login.')
  980.         
  981.     except:
  982.         rcfile is not None
  983.  
  984.     
  985.     try:
  986.         (userid, passwd, acct) = netrc.get_account(host)
  987.     except KeyError:
  988.         sys.stderr.write('No account -- using anonymous login.')
  989.  
  990.     ftp.login(userid, passwd, acct)
  991.     for file in sys.argv[2:]:
  992.         if file[:2] == '-l':
  993.             ftp.dir(file[2:])
  994.             continue
  995.         if file[:2] == '-d':
  996.             cmd = 'CWD'
  997.             if file[2:]:
  998.                 cmd = cmd + ' ' + file[2:]
  999.             
  1000.             resp = ftp.sendcmd(cmd)
  1001.             continue
  1002.         if file == '-p':
  1003.             ftp.set_pasv(not (ftp.passiveserver))
  1004.             continue
  1005.         ftp.retrbinary('RETR ' + file, sys.stdout.write, 1024)
  1006.     
  1007.     ftp.quit()
  1008.  
  1009. if __name__ == '__main__':
  1010.     test()
  1011.  
  1012.